package qeug.shsh.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.org.api.IOrgService;
import kd.bos.org.model.OrgParam;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.service.ServiceFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;
import kd.taxc.common.util.StringUtil;
import qeug.shsh.helper.FacadeHelper;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class DepartmentTaskPulgin extends AbstractTask {
    /**
     * 组织
     */
    private static final Log logs = LogFactory.getLog(SupplierToMDMTaskPlugin.class);

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
//    public void beforeItemClick(BeforeItemClickEvent evt) {//
//        String operationKey = evt.getOperationKey();
//        if ("donothing".equals(operationKey)) {//
        Map<String, Object> stringObjectMap = null;
        try {
            String json = FacadeHelper.postUrl("http://10.10.101.132:50000", "/RESTAdapter/CCS2HR/OrgSyn", stringObjectMap.toString());
//                String json = "{\n" +
//                        "    \"ORGINFO\": [\n" +
//                        "        {\n" +
//                        "            \"NUMBER\": \"0001\",\n" +
//                        "            \"NAME\": \"测试公司0001\",\n" +
//                        "            \"PARENTNUMBER\": \"5100\",\n" +
//                        "            \"ORGTYPE\": \"2\",\n" +
//                        "            \"STATUS\": 1,\n" +
//                        "            \"LASTUPDATETIIME\": \"20240411\",\n" +
//                        "            \"COSTCENTERS\": [\n" +
//                        "                {\n" +
//                        "                    \"COSTNUMBER\": \"001\",\n" +
//                        "                    \"COSTNAME\": \"行政组织\"\n" +
//                        "                }\n" +
//                        "            ]\n" +
//                        "        }\n" +
//                        "    ]\n" +
//                        "}";
            JSONArray jsonArray = JSONObject.parseObject(json).getJSONArray("ORGINFO");
            for (int i = 0; i < jsonArray.size(); i++) {
                //记录接口日志
                HashMap<String, Object> log = new HashMap<>();
                log.put("operationModule", "HR组织接口");
                log.put("url", "http://10.10.101.132:50000/RESTAdapter/CCS2HR/OrgSyn");
                log.put("user", System.getProperty("hr.user"));
                log.put("mode", "POST");
                log.put("action", "");
                log.put("opdate", new Date());
                log.put("mainstring", json);

                StringBuffer stringBuffer = new StringBuffer();
                JSONObject data = jsonArray.getJSONObject(i);
                String number = data.getString("NUMBER");//编码
                String name = data.getString("NAME");//姓名
                String parentNumber = data.getString("PARENTNUMBER");//上级组织编码
                String orgType = data.getString("ORGTYPE");//组织类型
                String status = data.getString("STATUS");//状态
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                String lastupdatetiime = data.getString("LASTUPDATETIIME");//最后修改时间
                LocalDate lastUpdateTime = LocalDate.parse(lastupdatetiime, formatter);
                JSONArray costCenters = data.getJSONArray("COSTCENTERS");//成本中心分录

                if (!StringUtil.isNotEmpty(number)) {
                    stringBuffer.append("组织编码不能为空！");
                }
                if (!StringUtil.isNotEmpty(name)) {
                    stringBuffer.append("组织名称不能为空！");
                }
                if (!StringUtil.isNotEmpty(parentNumber)) {
                    stringBuffer.append("上级组织编码不能为空！");
                }
                if (!StringUtil.isNotEmpty(orgType)) {
                    stringBuffer.append("组织类型不能为空！");
                }
                if (!StringUtil.isNotEmpty(status)) {
                    stringBuffer.append("状态不能为空！");
                }
                if (lastUpdateTime == null) {
                    stringBuffer.append("最后修改时间不能为空！");
                }
                if (stringBuffer.length() > 0) {
                    log.put("responsebody", stringBuffer);
                    log.put("pdesc", "失败");
                    FacadeHelper.apiLog(log);
                    continue;
                }

                DynamicObject adminOrg = BusinessDataServiceHelper.
                        loadSingle("bos_adminorg", new QFilter("number", "=", number).toArray());
//                    ORM orm = ORM.create();
//                    DynamicObject adminOrg = orm.newDynamicObject("bos_adminorg");
//                    adminOrg = org;
//                    if (org != null) {//判断人员是否存在
//                    }
                if (adminOrg == null) {
                    //组织编码在组织中未找到，新增组织
                    List<OrgParam> paramList = new ArrayList<>();
                    // 新增单个视图方案的组织
                    OrgParam param = new OrgParam();
                    DynamicObject parent = BusinessDataServiceHelper.
                            loadSingle("bos_adminorg", new QFilter("number", "=", parentNumber).toArray());
                    param.setParentId(parent.getLong("id"));//上级组织
                    param.setName(name);//组织名称
                    param.setNumber(number);//组织编码
                    if ("1".equals(orgType)) {
                        param.setOrgPatternId(7L);//集团
                    } else if ("2".equals(orgType)) {
                        param.setOrgPatternId(1L);//公司
                    } else if ("3".equals(orgType)) {
                        param.setOrgPatternId(4L);//部门
                    }//组织类型
                    param.setDuty(OrgViewType.Admin);

                    // 设置组织属性
                    Map<String, Object> proMap = new HashMap<>();
                    if ("1".equals(status)) {
                        proMap.put("enable", "1");//启用
                        proMap.put("status", "C");//已审核
                    } else if ("2".equals(status)) {
                        proMap.put("enable", "0");//停用
                        proMap.put("status", "A");//暂存
                    }//状态
                    param.setPropertyMap(proMap);
                    paramList.add(param);

/*                        //新增多视图方案的组织
                        param = new OrgParam();
                        param.setName(name);
                        param.setNumber(number);
                        param.setOrgPatternId(1);
                        // 设置多视图参数
                        TreeMap<String, OrgDutyView> multiViewMap = new TreeMap<>();
                        OrgDutyView dutyView = new OrgDutyView();
                        dutyView.setParentId(parent.getLong("id"));
                        multiViewMap.put(OrgViewType.Produce, dutyView);
                        // 每种视图方案的参数对象不能用同一个，需要单独实例化
                        dutyView = new OrgDutyView();
                        dutyView.setParentId(parent.getLong("id"));
                        multiViewMap.put(OrgViewType.Asset, dutyView);
                        param.setMultiViewMap(multiViewMap);
                        paramList.add(param);*/

                    // 业务调用可以参照接口名，以下举例说明微服务调用方式
                    IOrgService orgService = ServiceFactory.getService(IOrgService.class);
                    orgService.addOrUpdate(paramList);
                    //orgService.update(paramList);
                    System.out.println();
                    // 判断执行结果
                    for (OrgParam result : paramList) {
                        if (!Objects.equals(result.getMsg(), "")) {
                            //错误
                            logs.info("组织接口调用失败，错误原因：" + result.getMsg());
                            log.put("responsebody", result.getMsg());
                            log.put("pdesc", "失败");
                            FacadeHelper.apiLog(log);
                            System.out.println();
                        } else {
                            //成功
                            logs.info("组织接口调用成功");
                            log.put("responsebody", param);
                            log.put("pdesc", "成功");
                            FacadeHelper.apiLog(log);
                            System.out.println();
                            if ("1".equals(status)) {
                                for (int x = 0; x < costCenters.size(); x++) {
                                    JSONObject costCenter = costCenters.getJSONObject(x);
                                    String costNumber = costCenter.getString("COSTNUMBER");//成本中心编码
                                    String costName = costCenter.getString("COSTNAME");//成本中心名称
                                    // 人员新增修改成功在成本中心部门字段中添加部门
                                    QFilter f1 = new QFilter("number", "=", costNumber);
                                    QFilter f2 = new QFilter("name", "=", costName);
                                    QFilter[] f = new QFilter[]{f1, f2};
                                    //通过编码查询成本中心
                                    DynamicObject cost = BusinessDataServiceHelper.loadSingle("bos_costcenter", f);
                                    DynamicObject adminOrg1 = cost.getDynamicObject("qeug_adminorg");//成本中心部门
                                    String number1 = param.getNumber();
                                    QFilter f3 = new QFilter("number", "=", number1);
                                    DynamicObject costs = BusinessDataServiceHelper.loadSingle("bos_adminorg", f3.toArray());
                                    if (adminOrg1 != null) {
                                        String name1 = adminOrg1.getString("name");//成本中心部门名称
                                        if (!name1.equals(name)) {
                                            cost.set("qeug_adminorg", costs);
                                            logs.info("成本中心部门替换成功");
                                        }
                                    } else {
                                        cost.set("qeug_adminorg", costs);
                                        logs.info("成本中心部门添加成功");
                                    }

                                    OperationResult ces = SaveServiceHelper.saveOperate("bos_costcenter", new DynamicObject[]{cost}, OperateOption.create());//修改
                                    System.out.println();
                                }
                            }
                        }
                    }
                } else {
                    //修改组织数据
                    adminOrg.set("fisadministrative", "1");
//                        DynamicObject parentOrg = BusinessDataServiceHelper.
//                                loadSingle("bos_adminorg", new QFilter("number", "=", parentNumber).toArray());
//                        adminOrg.set("parent", parentOrg.getLong("id"));
                    if ("1".equals(orgType)) {
                        DynamicObject Orgform01 = BusinessDataServiceHelper.
                                loadSingle("bos_org_pattern", new QFilter("number", "=", "Orgform01").toArray());
                        adminOrg.set("orgpattern", Orgform01);//集团
                    } else if ("2".equals(orgType)) {
                        DynamicObject Orgform02 = BusinessDataServiceHelper.
                                loadSingle("bos_org_pattern", new QFilter("number", "=", "Orgform02").toArray());
                        adminOrg.set("orgpattern", Orgform02);//公司
                    } else if ("3".equals(orgType)) {
                        DynamicObject Orgform06 = BusinessDataServiceHelper.
                                loadSingle("bos_org_pattern", new QFilter("number", "=", "Orgform06").toArray());
                        adminOrg.set("orgpattern", Orgform06);//部门
                    }//组织类型
                    if ("1".equals(status)) {
                        adminOrg.set("enable", "1");//启用//使用状态
                        adminOrg.set("status", "C");//已审核//数据状态
                    } else if ("2".equals(status)) {
                        adminOrg.set("enable", "0");//停用//使用状态
                        adminOrg.set("status", "A");//暂存//数据状态
                    }
                    OperationResult bos_adminorg = SaveServiceHelper.saveOperate("bos_adminorg", new DynamicObject[]{adminOrg}, OperateOption.create());//新增、修改
                    System.out.println();
                    if (bos_adminorg.isSuccess()) {
                        //成功
                        log.put("responsebody", bos_adminorg);
                        log.put("pdesc", "成功");
                        FacadeHelper.apiLog(log);
                        System.out.println();
                        if ("1".equals(status)) {
                            // 组织新增修改成功在成本中心部门字段中添加修改部门
                            for (int x = 0; x < costCenters.size(); x++) {
                                JSONObject costCenter = costCenters.getJSONObject(x);
                                String costNumber = costCenter.getString("COSTNUMBER");//成本中心编码
                                String costName = costCenter.getString("COSTNAME");//成本中心名称
                                QFilter f1 = new QFilter("number", "=", costNumber);
                                QFilter f2 = new QFilter("name", "=", costName);
                                QFilter[] f = new QFilter[]{f1, f2};
                                //通过编码名称查询成本中心
                                DynamicObject cost = BusinessDataServiceHelper.loadSingle("bos_costcenter", f);
                                DynamicObject adminOrg1 = cost.getDynamicObject("qeug_adminorg");//成本中心部门
                                QFilter f3 = new QFilter("number", "=", number);
                                DynamicObject costs = BusinessDataServiceHelper.loadSingle("bos_adminorg", f3.toArray());
                                if (adminOrg1 != null) {
                                    String name1 = adminOrg1.getString("name");
                                    if (!name1.equals(name)) {
                                        cost.set("qeug_adminorg", costs);
                                    }
                                } else {
                                    cost.set("qeug_adminorg", costs);
                                }
                                OperationResult ces = SaveServiceHelper.saveOperate("bos_costcenter", new DynamicObject[]{cost}, OperateOption.create());//修改
                                System.out.println();
                            }
                        }
                    } else {
                        //错误
                        log.put("responsebody", bos_adminorg);
                        log.put("pdesc", "失败");
                        FacadeHelper.apiLog(log);
                        System.out.println();
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}